package smstpl

import (
	"context"
	"gitee.com/bobo-rs/creative-services/consts"
	"gitee.com/bobo-rs/creative-services/enums"
	"gitee.com/bobo-rs/creative-services/framework/dao"
	"gitee.com/bobo-rs/creative-services/framework/model"
	"gitee.com/bobo-rs/creative-services/framework/model/entity"
	"gitee.com/bobo-rs/creative-services/framework/service"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// CurrSyncOutFromTemplateStatus 同步当前SMS平台模板状态
func (t *sSmsTpl) CurrSyncOutFromTemplateStatus(ctx context.Context) error {
	fromType, err := t.CurrFromSmsDriver(ctx)
	if err != nil {
		return err
	}
	// 同步数据
	return t.SyncOutFromTemplateStatus(ctx, *fromType)
}

// CurrApplyOutFromTemplate 同步当前SMS服务模板到外部平台
func (t *sSmsTpl) CurrApplyOutFromTemplate(ctx context.Context, tid uint) error {
	fromType, err := t.CurrFromSmsDriver(ctx)
	if err != nil {
		return err
	}
	// 同步数据
	return t.ApplyOutFromTemplate(ctx, tid, *fromType)
}

// CurrTemplateByAlias 通过模板变量获取当前模板信息-模板ID和模板内容（发送短信）
func (t *sSmsTpl) CurrTemplateByAlias(ctx context.Context, varAlias enums.SmsAlias) (*model.CurrTemplateItem, error) {
	// 获取模板数据
	item := &model.CurrTemplateItem{}
	err := t.TemplateModel().Scan(ctx, g.Map{
		dao.SmsTemplate.Columns().VarAlias: varAlias,
		dao.SmsTemplate.Columns().Status:   enums.SmsStatusOk,
	}, &item)
	if err != nil {
		return nil, gerror.Wrapf(err, `模板不存在%s`, err)
	}

	// 获取当前模板ID
	templateId, err := t.CurrTemplateIdByAlias(ctx, varAlias)
	if err != nil {
		return nil, err
	}
	item.TemplateId = *templateId
	return item, nil
}

// CurrTemplateIdByAlias 通过模板变量获取当前配置SMS服务模板ID
func (t *sSmsTpl) CurrTemplateIdByAlias(ctx context.Context, varAlias enums.SmsAlias) (*string, error) {
	// 获取当前SMS服务
	fromType, err := t.CurrFromSmsDriver(ctx)
	if err != nil {
		return nil, err
	}
	return t.ProcessTemplateIdByAliasAndFrom(ctx, string(varAlias), *fromType)
}

// CurrTemplateOutMapByAlias 通过模板变量获取当前SMS平台模板MAP
func (t *sSmsTpl) CurrTemplateOutMapByAlias(ctx context.Context, varAlias ...string) (map[string]*entity.SmsTemplateOut, error) {
	// 获取当前SMS服务
	fromType, err := t.CurrFromSmsDriver(ctx)
	if err != nil {
		return nil, err
	}
	return t.ProcessTemplateOutMapByAlias(ctx, *fromType, varAlias...)
}

// CurrFromSmsDriver 获取短信平台SMS驱动
func (t *sSmsTpl) CurrFromSmsDriver(ctx context.Context) (*string, error) {
	// 获取当前SMS服务
	fromType := service.Config().String(ctx, consts.SysConfigSmsDriver)
	if len(fromType) == 0 {
		return nil, gerror.New(`SMS服务未配置，请先到后台系统进行配置`)
	}
	return &fromType, nil
}
